const { uniqueId } = require("lodash")
const moment = require("moment")

module.exports = app => {
  const BaseController = require("@wangpengxiang/aegis").Controller.Base(app)
  let productList = [
    {
      product_id:
        "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
      product_name: `《大前端面试宝典》`,
      price: 39.9,
      inventory: 99999,
      create_time: "2023-07-03 20:23:22",
    },
    {
      product_id: uniqueId(),
      product_name: `《前端求职之道》`,
      price: 199,
      inventory: 10000000,
      create_time: "2024-08-03 10:43:22",
    },
    {
      product_id: uniqueId(),
      product_name: `《大前端全栈实践》`,
      price: 899,
      inventory: 188888,
      create_time: "2025-09-23 15:03:30",
    },
  ];

  return class BusinessController extends BaseController {
    async getList(ctx) {
      this.success(ctx, productList, {
        total: productList.length,
      })
    }

    async remove(ctx) {
      const { product_id: productId } = ctx.request.body
      productList = productList.filter(product => product.product_id !== productId)
      this.success(ctx, {
        projKey: ctx.projKey,
        productId,
      })
    }

    async getProductEnumList(ctx) {
      this.success(ctx, [
        {
          label: "《大前端面试宝典》",
          value: "《大前端面试宝典》",
        },
        {
          label: "《前端求职之道》",
          value: "《前端求职之道》",
        },
        {
          label: "《大前端全栈实践》",
          value: "《大前端全栈实践》",
        },
      ]);
    }

    async create(ctx) {
      const { product_name: productName, price, inventory } = ctx.request.body
      const productId = uniqueId()
      const product = { product_id: productId, product_name: productName, price, inventory, create_time: moment(Date.now()).format("YYYY-MM-DD HH:mm:ss") }
      productList.push(product)
      this.success(ctx, product)
    }

    async get(ctx) {
      const { product_id } = ctx.query
      const product = productList.find(product => product.product_id === product_id)
      product ? this.success(ctx, product) : this.fail(ctx, "暂无匹配数据", 442)
    }

    async edit(ctx) {
      const { product_id, price, inventory, product_name } = ctx.request.body
      const product = productList.find(product => product.product_id === product_id)
      if (product) {
        product.product_name = product_name
        product.price = price
        product.inventory = inventory
      } else {
        return this.fail(ctx, "暂无匹配数据", 442)
      }
      this.success(ctx, {
        product_id,
      })
    }
  }
}
